<template>
  <el-dialog :title="title" v-model="drawer" width="700px" :append-to-body="true" @close="close">
    <el-form :model="form" size="small" label-width="100px" ref="ruleRefForm" :rules="rules">
        <el-form-item label="上级分类" prop="parentId">
            <el-cascader v-model="form.parentId" :options="classify" :props="{value: 'id', label: 'name', checkStrictly: true, children: 'class'}"></el-cascader>
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
            <el-input placeholder="请输入分类名称" v-model="form.name" style="width:182px"></el-input>
        </el-form-item>
        <el-form-item label="分类图标" prop="icon">
            <el-upload
                ref="upload"
                v-model:file-list="form.images"
                :action="action"
                list-type="picture-card"
                :headers="headers"
                accept="image/*"
                :limit="1"
                :on-preview="handlePictureCardPreview"
                :on-exceed="handleExceed"
                :on-remove="handleRemove"
                :on-success="imagesOnSuccess"
            >
                <el-icon><ele-Plus /></el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
            <el-input-number v-model="form.sort" :min="0" step-strictly :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="showStatus">
            <el-radio-group v-model="form.showStatus">
                <el-radio :label="1">显示</el-radio>
                <el-radio :label="0">隐藏</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleRefForm)">提交</el-button>
            <el-button @click="resetForm(ruleRefForm)">取消</el-button>
        </el-form-item>
    </el-form>
    <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </el-dialog>
</template>

<script>
import { computed, reactive, toRefs, ref } from 'vue'
import { genFileId ,ElMessage} from 'element-plus'
import {getCategoryTree,create,update} from  '/@/api/pms/category'
import { Session } from '/@/utils/storage';
export default {
    name: 'ClassifyDetail',
    props: {
        title: {
            type: String,
            default: '新增分类'
        },
        dialogDrawer: {
            type: Boolean,
            default: false
        },
        defaultForm: {
            type: Object,
            default: () => {
                return {}
            }
        },
        classifyList: {
            type: Array,
            default() {
                return []
            }
        }
    },
    emits: ['onDetailSubmit'],
    setup(props, context) {
        const { dialogDrawer, defaultForm, classifyList } = toRefs(props)
        const drawer = computed({
            get: () => dialogDrawer.value,
            set: val => {
                context.emit('update:dialogDrawer', val)
            }
        })
        const form = computed({
            get: () => {
                return defaultForm.value
            },
            set: val => {
                context.emit('update:defaultForm', val)
            }
        })
        const classify = computed(() => {
            return classifyList.value
        })
        const ruleRefForm = ref()
        const upload = ref()
        const close = () => {
            context.emit('update:dialogDrawer', false)
        }
        const chooseClassifyImage = () => {

        }
        const state = reactive({
            rules: {
                name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
            },
            icon: [],
            action: '/api/file/filaAttach/upload',
            headers: {
                '17work': Session.get('token')
            },
            dialogVisible: false,
            dialogImageUrl: ''
        })
        const submitForm = async (formEl) => {
            if (!formEl) return
            await formEl.validate((valid) => {
                if (valid) {
					let data = form.value
					let parentId = 0
					if(data.parentId.length > 1){
						parentId = data.parentId[1]
					}else{
						parentId = data.parentId[0]
					}
					data.parentId = parentId
					// 修改
					if(data.id!=null && data.id!= ''){
					 update(data).then(res=>{
						 if(res.code == 0){
							ElMessage.success("修改成功");
							context.emit('onDetailSubmit', true)
						 }else{
							ElMessage.error("修改失败");
						 }
					 })

					}
					// 新增
					else{
						create(data).then(res=>{
							if(res.code == 0){
							 ElMessage.success("添加成功");
							 context.emit('onDetailSubmit', true)
							}else{
							 ElMessage.error("添加失败");
							}
						})

					}
                }
            })
        }
        const resetForm = (formEl) => {
            if (!formEl) return
            context.emit('update:dialogDrawer', false)
            formEl.resetFields()
        }
        const handlePictureCardPreview = (uploadFile) => {
            state.dialogImageUrl = uploadFile.url
            state.dialogVisible = true
        }
        const handleExceed = (files) => {
            upload.value.clearFiles()
            const file = files[0]
            file.uid = genFileId()
            upload.value.handleStart(file)
        }
        const handleRemove = () => {
            form.value.icon = ''
        }
        const imagesOnSuccess = (response, uploadFiles) => {
            console.log(response);
            form.value.icon = response.data.src
        }
        return {
            drawer,
            close,
            form,
            classify,
            chooseClassifyImage,
            ruleRefForm,
            submitForm,
            resetForm,
            handlePictureCardPreview,
            handleExceed,
            upload,
            handleRemove,
            imagesOnSuccess,
            ...toRefs(state)
        }
    }
}
</script>

<style scoped lang="scss">
.item-row {
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f9f9f9;
    cursor: pointer;
    width: 60px;
    height: 60px;
    border: 1px dashed #eee;
    font-size: 18px;
    color: #666;
}
</style>
